<template>
  <div v-if="isLoading">......</div>
  <iframe v-else id="child" v-show="isUpdate" :src="webViewUrl" :style="{ ...style }" :key="viewKey"></iframe>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'

interface Props {
  url: string
}

const props = withDefaults(defineProps<Props>(), {
  url: '',
})

const isLoading = ref(false)
const srcUrl = ref(props.url)
const webViewUrl = ref(window.location.origin + props.url + window.location.search)


const style = ref({
  width: '30rem', 
  height: '100vh', 
  position: 'absolute', 
  top: 0, 
  left: '0',
  margin: 'auto',
  maxWidth: '100%',
  border: 'none',
})

const isUpdate = ref(true)
const viewKey = ref(1)
const updated = ref(false)
const { t } = useI18n()

const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)

const updateWidthAndHeight = () => {
  updated.value = true
  const systemInfo = uni.getSystemInfoSync()
  const systemInfoWidth = window.innerWidth || 0 
  const systemInfoHeight = window.innerHeight || 0 

  if (isMobile) {
    console.log('')
    style.value.position = 'fixed' 
    style.value.width = systemInfoWidth > 450 ? '100%' : '30rem'
    style.value.height = systemInfoHeight + 'px' 
  } else {
    isUpdate.value = false
    console.log('pc')
    
    if (systemInfo.windowWidth >= 768 && systemInfo.windowWidth < 960) {
      style.value.maxWidth = '60%'
    } else if (systemInfo.windowWidth >= 480 && systemInfo.windowWidth < 768) {
      style.value.maxWidth = '70%'
    } else if (systemInfo.windowWidth >= 320 && systemInfo.windowWidth < 480) {
      style.value.maxWidth = '80%'
    } else if (systemInfo.windowWidth >= 0 && systemInfo.windowWidth < 320) {
      style.value.maxWidth = '90%'
    } else {
      style.value.maxWidth = '30rem'
      style.value.left = '40%'
    }
    
    
    
    isUpdate.value = true
    viewKey.value = viewKey.value + 1
  }
}


window.addEventListener(
  'message',
  (event) => {
    isLoading.value = true
    srcUrl.value = event.data
    webViewUrl.value = event.origin + event.data
    console.log(event.origin + event.data)
    if (isMobile) {
      console.log('event.data', event.data)
      uni.navigateTo({
        url: event.data,  
      });
    } else {
      window.location.href = event.data
    }

    isLoading.value = false
  },
  false
)


onMounted(() => {
  if (!updated.value) updateWidthAndHeight()
  window.addEventListener('resize', updateWidthAndHeight) 
})

onUnmounted(() => {
  window.removeEventListener('resize', updateWidthAndHeight) 
})
</script>

<style lang="scss" scoped>
</style>
